<template>
  <div class="disLibraryList padding_20">
    <el-input v-model="searchCondition"
              placeholder="请输入名称"
              class="w-200"
              clearable
              @clear="handleQuery"/>
    <el-button type="primary"
               @click="handleQuery">查 询
    </el-button>
    <el-button type="primary"
               @click="handleAdd">新 增
    </el-button>
    <Table :columns="tableCol"
           :data="tableData"
           stripe
           border
           class="mt-20">
      <template slot-scope="{row,index}"
                slot="action">
        <span @click="handleEdit(row)">编辑</span>
        <span @click="handleDel(row)">删除</span>
      </template>
    </Table>
    <page @getList="_getList"
          :pageTotal="pageTotal"
          ref="page"></page>

    <el-dialog :title="title"
               width="30%"
               :close-on-click-modal="false"
               :visible.sync="dialogFormVisible">
      <el-form :model="editModel"
               :rules="formRules"
               ref="formRefs">
        <el-form-item :label-width="formLabelWidth" class="is-required"
                      label="图标">
          <el-upload class="avatar-uploader"
                     :action="imageUploadUrl"
                     :show-file-list="false"
                     :on-success="handleAvatarSuccess"
                     :before-upload="beforeAvatarUpload">
            <img v-if="editModel.imageUrl"
                 :src="editModel.imageUrl"
                 width="100px"
                 height="100px"
                 class="avatar">
            <i v-else
               class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" class="is-required"
                      label="名称">
          <el-input v-model="editModel.name"
                    placeholder="请输入名称"></el-input>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" class="is-required"
                      label="排序号">
          <el-input v-model="editModel.sortNum"
                    placeholder="请输入排序号"></el-input>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth"
                      label="介绍">
          <el-input v-model="editModel.desp"
                    type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="handleSave()">保 存
        </el-button>
      </div>
    </el-dialog>
    <el-dialog title="图标"
               center
               :visible.sync="imageModal"
               width="30%">
      <img :src="imageUrl"
           style="width:100%;height:100%">
      <span slot="footer">
        <el-button type="primary"
                   @click="imageModal = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Page from '@/base/page/page'
import {mapGetters} from 'vuex'

export default {
  name: "departmentList",
  data() {
    return {
      imageModal: false,
      imageUrl: null,
      title: '新增科室',
      dialogFormVisible: false,
      formLabelWidth: '120px',
      imageUploadUrl: this.api.file.upload,
      tableCol: [
        {
          type: 'index2',
          title: '',
          width: 60,
          render: (h, params) => {
            return h('span', params.index + (this.page.pageIndex) * this.page.pageSize + 1);
          }
        },
        {
          title: '图标',
          key: 'imageUrl',
          width: 95,
          render: (h, params) => {
            return h('div', [
              h('img', {
                attrs: {
                  src: params.row.imageUrl
                },
                style: {
                  width: '60px',
                  height: '60px',
                  'border-radius': '50%'
                },
                on: {
                  click: (event) => {
                    this.showBigImage(params.row.imageUrl);
                  }
                }
              }),
            ]);
          }
        },
        {
          title: '名称',
          key: 'name'
        },
        {
          title: '排序号',
          key: 'sortNum'
        },
        {
          title: '介绍',
          key: 'desp'
        },
        {
          title: '修改时间',
          key: 'name',
          render: (h, params) => {
            return h('span',
              this.commonFunction.timestampFormat(new Date(params.row.lastUpdateTime), 'yyyy-MM-dd hh:mm:ss'));
          }
        },
        {
          title: '操作',
          slot: 'action',
          align: 'center'
        }],
      tableData: [],
      pageTotal: 0,       //总条数
      searchCondition: '',
      editModel: {
        id: null,
        name: '',
        sortNum: '',
        desp: '',
        imageUrl: ''
      },
      formRules: {
        imageUrl: [{required: true, message: '请上传图标'}],
        name: [{required: true, message: '请输入名称'}],
        sortNum: [{required: true, message: '请输入排序号'}],
      }
    }
  },
  mounted() {
    this._getList()
  },
  methods: {
    showBigImage(url) {
      this.imageUrl = url;
      this.imageModal = true;
    },
    handleQuery() {
      this.page.pageIndex = 0;
      this._getList();
    },
    handleAdd() {
      this.handleEdit();
    },
    handleEdit(row) {
      if (row) {
        this.$nextTick(() => {
          this.$refs.formRefs.resetFields();
        });
        this.editModel = Object.assign({}, row);
        this.title = '编辑科室';
      } else {
        this.editModel = {};
        this.$nextTick(() => {
          this.$refs.formRefs.resetFields();
        })
        this.title = '新增科室';
      }
      this.dialogFormVisible = true;
    },
    handleSave() {
      if (!this.editModel.imageUrl) {
        this.$message.warning('请上传头像')
      } else if (!this.editModel.name) {
        this.$message.warning('请输入名称')
      } else if (!this.editModel.sortNum) {
        this.$message.warning('请输入排序')
      } else {
        this.post(this.api.department.uploadDepartment, this.editModel).then((res) => {
          if (res.data.code === '200') {
            this._getList();
            this.$message.success('操作成功!');
            this.dialogFormVisible = false;
          }
        });
      }

      // this.$refs.formRefs.validate((valid) => {
      //   if (valid) {
      //     this.post(this.api.department.uploadDepartment, this.editModel).then((res) => {
      //       if (res.data.code === '200') {
      //         this._getList();
      //         this.$message.success('操作成功!');
      //         this.dialogFormVisible = false;
      //       }
      //     });
      //   }
      // })

    },
    handleDel(row) {
      this.$confirm('确认删除？')
        .then(_ => {
          this.post(this.api.department.deleteDepart, {id: row.id}).then((res) => {
            if (res.data.code === '200') {
              this.$message.success('删除成功!');
              this._getList();
            }
          });
        })
        .catch(_ => {
        });
    },
    _getList() {
      let param = {
        pageIndex: this.page.pageIndex,
        pageSize: this.page.pageSize,
        name: this.searchCondition
      }
      this.post(this.api.department.getDepartPageApp, param).then((res) => {
        if (res.data.code === '200') {
          this.tableData = res.data.object;
          this.pageTotal = res.data.totalNum;
        }
      });
    },
    handleAvatarSuccess(res) {
      if (res.code === '200') {
        this.$set(this.editModel, 'imageUrl', res.object[0]);
        this.$message.success('上传成功!');
        this.$forceUpdate()
      } else {
        this.$message.success(res.message);
      }
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      let types = ['image/jpeg', 'image/jpg', 'image/gif', 'image/png', 'image/bmp']
      const isType = types.includes(file.type);
      if (!isType) {
        this.$message.error('上传图片必须是JPG/JPEG/GIF/PNG/BMP 格式!');
        return isType;
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
      }
      return isLt2M;
    },
  },
  computed: {
    ...mapGetters([
      'page'
    ])
  },
  components: {
    Page,
  }
}
</script>

<style scoped>
/deep/ .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 15px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>
